﻿using System.Collections.Generic;
using System.Linq;
using Missbot.Common;
using Missbot.Core.Base;
using Missbot.Core.Cache;
using Missbot.Core.Common;
using Dolany.UtilityTool;
using JetBrains.Annotations;
using Missbot.AIModule.Base;

namespace Missbot.AIModule.SingleCommand.Fortune
{
    [UsedImplicitly]
    public class MajFortuneMod : IAIModule, IDataMgr
    {
        public override string Name => "麻将运势";

        private readonly string[] PosArray = { "东", "南", "西", "北" };

        private Dictionary<string, string> CharactorsDic { get; set; } = new();
        private Dictionary<string, int> KindDic = new();

        public void RefreshData()
        {
            CharactorsDic = MajCharactorDA.GetAll().ToDictionary(p => p.Name, p => p.FileID);
            KindDic = MajBonusDA.GetAll().ToDictionary(p => p.Name, p => p.Rate);
        }

        [ModuleEnter(Command = "麻将运势", Description = "获取今日的麻将运势")]
        public bool RandomMajFortune(InboxSession session)
        {
            var fortune = RapidCacher.GetCache($"MajFortune:{session.User.ID}", CommonUtil.UntilTommorow(), () => NewFortune(session.User.ID));
            var buffer = new OutputBuffer(session);
            buffer.AddPair(new Dictionary<string, string>
            {
                ["今日麻将运势"] = "",
                ["整体运势"] = LevelHelper.LevelToStars(fortune.FortuneStar),
                ["吉位"] = fortune.Position,
                ["牌运"] = fortune.Kind,
                ["代表人物"] = fortune.CharactorName
            });
            buffer.AddFile(fortune.FileID);

            buffer.Send();
            return true;
        }

        private MajFortuneCache NewFortune(string UserID)
        {
            var fortuneStar = Rander.RandInt(11);
            var position = PosArray.RandElement();
            var kind = KindDic.RandRated();
            var (key, value) = CharactorsDic.RandElement();

            return new MajFortuneCache
            {
                CharactorName = key,
                FileID = value,
                FortuneStar = fortuneStar,
                Kind = kind,
                Position = position,
                UserID = UserID
            };
        }
    }
}